<template>
  <div class="dashboard">
    <h1>欢迎使用！{{ username }}</h1>

    <el-button type="primary" @click="showChangePasswordDialog">修改密码</el-button>
    <template v-if="isAdmin">
      <p>当前在职 {{ activeTeachers }} 位老师</p>
      <p>退休返聘 {{ retiredTeachers }} 位老师</p>
    </template>
    <el-dialog v-model="dialogVisible" title="修改密码" width="30%">
      <el-form :model="passwordForm" :rules="rules">
        <div class="form-item">
          <span class="form-label">新密码</span>
          <el-input v-model="passwordForm.newPassword" autocomplete="off" style="width: 100%;"
                    type="password"></el-input>
        </div>
        <div class="form-item">
          <span class="form-label">确认密码</span>
          <el-input v-model="passwordForm.confirmPassword" autocomplete="off" style="width: 100%;"
                    type="password"></el-input>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitChangePassword">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, onMounted, ref, onUnmounted} from 'vue';
import {useStore} from 'vuex';
import {ElMessage} from "element-plus";
import {changePassword} from '@/api/UserApi';
import {iget} from '@/api';

const store = useStore();
const username = computed(() => store.state.username + " 老师");
const isAdmin = computed(() => store.state.role === 'admin');
const activeTeachers = computed(() => store.state.activeTeachers || 0);
const retiredTeachers = computed(() => store.state.retiredTeachers || 0);

let teachersCountInterval = null;

const fetchTeachersCount = async () => {
  try {
    const activeResponse = await iget('/dashboard/getUserCount', {status: '在职'});
    const retiredResponse = await iget('/dashboard/getUserCount', {status: '退休返聘'});
    
    store.commit('setTeachersCount', {
      active: activeResponse.data.result,
      retired: retiredResponse.data.result
    });
  } catch (error) {
    console.log('获取教师数量失败'+error);
  }
};

onMounted(async () => {
  if (isAdmin.value) {
    await fetchTeachersCount();
    teachersCountInterval = setInterval(fetchTeachersCount, 20000);
  }
});

onUnmounted(() => {
  if (teachersCountInterval) {
    clearInterval(teachersCountInterval);
  }
});

const dialogVisible = ref(false);
const passwordForm = ref({
  newPassword: '',
  confirmPassword: ''
});

const validatePassword = (value, callback) => {
  const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/;
  if (!passwordRegex.test(value)) {
    callback(new Error('密码必须包含数字和字母，且长度在8到16位之间'));
    return false;
  }
  if (passwordForm.value.confirmPassword !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'));
    return false;
  }
  return true;
};


const showChangePasswordDialog = () => {
  dialogVisible.value = true;
};

const submitChangePassword = async () => {


  try {
    if (!validatePassword(
        passwordForm.value.newPassword,
        (error) => {
          if (error) {
            ElMessage.error(error.message);
          }
        }
    )) {
      return;
    }
    const formData = {
      password: passwordForm.value.newPassword
    };
    passwordForm.value.newPassword = '';
    passwordForm.value.confirmPassword = '';
    await changePassword(formData);
  } finally {
    dialogVisible.value = false;
  }
};
</script>

<style scoped>
.dashboard {
  padding: 20px;
  text-align: center;
}

h1 {
  font-size: 2em;
  margin-bottom: 20px;
}

p {
  font-size: 1.2em;
  color: #666;
  margin-bottom: 10px;
}

/* 新增样式确保输入框对齐 */
.form-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.form-label {
  width: 100px; /* 设置标签宽度一致 */
  text-align: left; /* 左对齐 */
  display: flex;
  align-items: center; /* 垂直居中 */
}

.el-input {
  width: 100%;
}
</style>
